package cc.sheji.service;


import cc.sheji.config.DeviceConfig;
import cc.sheji.domain.*;
import cc.sheji.exception.CreateJobRuleException;
import cc.sheji.exception.TooMoreActionException;
import cc.sheji.exception.TranslateException;
import cc.sheji.reposity.CategoryRepository;
import cc.sheji.reposity.JobRepository;
import cc.sheji.reposity.NoticeRepository;
import cc.sheji.reposity.UserRepository;
import cc.sheji.util.CompareUtil;
import cc.sheji.util.HttpUtil;
import cc.sheji.util.StateCallBack;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class JobService {

    @Autowired
    JobRepository jobRepository;


    @Autowired
    HttpUtil httpUtil;

    @Autowired
    AsynService asynService;

    @Autowired
    DeviceConfig deviceConfig;

    Long lastDotask1 = 0L;
    Long lastDotask2 = 0L;
    Long lastDotask3 = 0L;
    Long lastDotask4 = 0L;

    private String doTaskUrl = "https://discord.com/api/v9/interactions";

    @Autowired
    NoticeRepository noticeRepository;

    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    CompareUtil compareUtil;
    String uploadUrl="https://www.shejiai.cc/api/v1/file/upload";
    @Value("${updataPath}")
    String updataPath;
    @Autowired
    CategoryRepository categoryRepository;
    static HashMap<String, String> whRaditoMap = new HashMap();

    static {
        whRaditoMap.put("1", " --ar 1:1");
        whRaditoMap.put("2", " --ar 1:2");
        whRaditoMap.put("3", " --ar 4:3");
        whRaditoMap.put("4", " --ar 3:4");
        whRaditoMap.put("5", " --ar 16:9");
        whRaditoMap.put("6", " --ar 9:16");
    }

    static HashMap<String, String> whRaditoMaps = new HashMap();

    static {
        whRaditoMaps.put("1", "1:1");
        whRaditoMaps.put("2", "1:2");
        whRaditoMaps.put("3", "4:3");
        whRaditoMaps.put("4", "3:4");
        whRaditoMaps.put("5", "16:9");
        whRaditoMaps.put("6", "9:16");
    }
    @Autowired
    UserRepository userRepository;
    private String doTaskUrl1 = "https://api.goapi.xyz/mj/v2/imagine";
    private String doTaskUrl2 = "https://api.goapi.xyz/mj/v2/blend";
    private String doTaskUrl3 = "https://api.goapi.xyz/mj/v2/fetch";
    private String doTaskUrl4 = "https://api.midjourneyapi.xyz/mj/v2/inpaint";

    private String Key = "64ba78a75936935a2a8d4ee72ab4c0bb84b3bc52029c4b62eddd9647a7097cba";
    public Job create(Job job) throws Exception {

        try {
            Optional<User> byId = userRepository.findById(job.getUserId());
            if(byId!=null){
                User user = byId.get();
                Integer continueTimeLock = user.getContinueTimeLock();
                if(continueTimeLock==null||continueTimeLock!=1){
                    user.setContinueTimeLock(1);
                    Integer continueTime = user.getContinueTime();
                    if(continueTime!=null&&continueTime>0){
                        continueTime++;
                    }else {
                        continueTime=1;
                    }
                    user.setContinueTime(continueTime);
                    Integer monthTime = user.getMonthTime();
                    if(monthTime!=null){
                        monthTime++;
                    }else {
                        monthTime=1;
                    }
                    user.setMonthTime(monthTime);
                    System.out.println("--------normal reach-------------");
                }
                System.out.println("--------normal reach1-------------");
            }
        }catch (Exception e){

            e.printStackTrace();
        }

//        String key = "job" + StpUtil.getLoginId();

//        redisTemplate.opsForValue().
//        if (redisTemplate.hasKey(key)) {
//            throw new TooMoreActionException();
//        }

        String[] attachImages = job.getAttachImages();
        boolean samePic = false;

//        if (attachImages != null) {
//            if (attachImages.length > 1)
//                for (int i = 0; i < attachImages.length; i++) {
//                    for (int k = i + 1; k < attachImages.length; k++) {
//                        String url1 = attachImages[i];
//                        String url2 = attachImages[k];
//                        url1 = url1.replaceAll("https://www.shejiai.cc:443/v1/image/", "");
//                        url2 = url2.replaceAll("https://www.shejiai.cc:443/v1/image/", "");
//                        url1 = updataPath + url1;
//                        url2 = updataPath + url2;
//                        if (compareUtil.compareFiles(url1, url2)) {
//                            samePic = true;
//                        }
//                    }
//                }
//        }
//
//        if (samePic) {
//            throw new CreateJobRuleException("不能上传一样图片");
//        }


//        redisTemplate.opsForValue().set(key, new Date(), 30, TimeUnit.SECONDS);
//        job.setId(null);
//        job.setUserId(StpUtil.getLoginIdAsLong());
        String cmd = "" + job.getCmd().replaceAll("  ", " ");
        List<Category> all = categoryRepository.findAll(null);
        if (all != null)
            for (Category category : all) {
                String name = category.getName();
                String englishName = category.getEnglishName();
                if (englishName != null && name != null)
                    cmd = cmd.replaceAll(name, englishName);
            }

        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(cmd);
        if (m.find()) {
            int time = 0;
            boolean finish = false;
            while (time < 3) {
                String translate = hanleEngligh(httpUtil.getToString(toEnglishUrl(cmd)));
                if (translate != null) {
                    finish = true;
                    cmd = translate;
                    break;
                }
                Thread.sleep(2000);
            }
            if (!finish)
                throw new TranslateException("翻译功能异常");
        }


        cmd = cmd.trim();
        String addCmd = "";
        if (cmd.length() != 0) {
            addCmd = addCmd + "" + cmd;
        }
        if (job.getStyle() != null) {
            try {
                Long styleId = Long.parseLong("" + job.getStyle());
                Optional<Category> byId = categoryRepository.findById(styleId);
                if (byId != null) {
                    Category category = byId.get();
                    if (category != null) {

                        String englishName = category.getEnglishName();
                        if (englishName != null && englishName.length() > 0)
                            addCmd = addCmd + " " + englishName;
                    }

                }
            } catch (Exception e) {
            }
        }
        addCmd = addCmd.replaceAll("-", " ");
        addCmd = addCmd.replace(" tile ", " --tile ");
        addCmd = addCmd.replace(" tile", " --tile");
        addCmd = addCmd.replaceAll("  ", " ");
        job.setFullTextCmd(addCmd);
        String badContent = job.getBadContent();
        if (badContent == null || badContent.toLowerCase().equals("null")) {
            badContent = "";
        }
        Matcher m1 = p.matcher(badContent);
        if (m1.find()) {
            int time = 0;
            boolean finish = false;
            while (time < 3) {
                String translate = hanleEngligh(httpUtil.getToString(toEnglishUrl(badContent)));
                if (translate != null) {
                    finish = true;
                    badContent = translate;
                    break;
                }
                Thread.sleep(2000);
            }
            if (!finish)
                throw new TranslateException("翻译功能异常");
        }
        badContent = badContent.replaceAll("-", " ");
        badContent = badContent.replaceAll("  ", " ");
        job.setBadContentFullText(badContent.trim());
        switch (job.getModule()) {
            case 4:
                addCmd += " --v 5.1";
                break;
            case 5:
                addCmd += " --v 5.2";
                break;
            case 6:
                addCmd += " --v 5 --niji 5";
                break;
            case 7:
                addCmd += " --v 5 --c 10";
                break;
            case 8:
                addCmd += " --v 5 ";
                break;
        }
        Job finalJob = job;
        //图片纵横比
        String whRatio = " --ar 1:1";
        String temRadio = whRaditoMap.get("" + job.getWidth2height());
        if (temRadio != null) {
            whRatio = temRadio;
        }
        Map<String, String> headers = new HashMap<>();
        headers.put("X-API-KEY", Key);
        if(job.getTaskType()==2){
            JSONObject jsonObj  = new JSONObject();
            jsonObj.put("origin_task_id",job.getTaskRelationId());
            jsonObj.put("index", job.getTaskTag());
            jsonObj.put("webhook_endpoint", "https://www.shejiai.cc/api/v1/job/"+job.getId());
            jsonObj.put("webhook_secret", "");
            jsonObj.put("notify_progress", true);
            String jsonstr =jsonObj.toJSONString();
            log.info("upscale请求参数"+jsonstr);
            httpUtil.postJsonToString("https://api.goapi.xyz/mj/v2/upscale", jsonstr, headers, new StateCallBack() {
                @Override
                public void onSuccess(String json) {
                    System.out.println("upscale task:" + json);
                    JSONObject jsonObject = JSONObject.parseObject(json);
                    finalJob.setDataResult(json);
                    finalJob.setTaskId(jsonObject.getString("task_id"));
                    finalJob.setTaskRelationId(jsonObject.getString("task_id"));
                    jobRepository.save(finalJob);
                }
                @Override
                public void onFail(String e) {
                    System.out.println("upscale请求参数 task error:" + e);
                    finalJob.setState(10);
                    finalJob.setErrorState(1);
                    finalJob.setNoticeState(1);
                    finalJob.setErrorMessages(e);
                    finalJob.setFinishTime(new Date());
                    jobRepository.save(finalJob);
                }
            });
        }
        if(job.getTaskType()==4){
            addCmd +=whRatio;
            addCmd +=badContent;
            JSONObject jsonObj  = new JSONObject();
            jsonObj.put("origin_task_id",job.getTaskRelationId());
            if (cmd.length() != 0) {
                jsonObj.put("prompt",addCmd);
            }
            jsonObj.put("webhook_endpoint", "https://www.shejiai.cc/api/v1/job/"+job.getId());
            jsonObj.put("webhook_secret", "");
            jsonObj.put("notify_progress", true);
            String jsonstr =jsonObj.toJSONString();
            log.info("重绘请求参数"+jsonstr);
            httpUtil.postJsonToString("https://api.goapi.xyz/mj/v2/reroll", jsonstr, headers, new StateCallBack() {
                @Override
                public void onSuccess(String json) {
                    System.out.println("upscale task:" + json);
                    JSONObject jsonObject = JSONObject.parseObject(json);
                    finalJob.setDataResult(json);
                    finalJob.setTaskId(jsonObject.getString("task_id"));
                    finalJob.setTaskRelationId(jsonObject.getString("task_id"));
                    jobRepository.save(finalJob);
                }
                @Override
                public void onFail(String e) {
                    System.out.println("upscale请求参数 task error:" + e);
                    finalJob.setState(10);
                    finalJob.setErrorState(1);
                    finalJob.setNoticeState(1);
                    finalJob.setErrorMessages(e);
                    finalJob.setFinishTime(new Date());
                    jobRepository.save(finalJob);
                }
            });
        }
        if(job.getTaskType()==1){
            //图片生成
            if(false){
                JSONObject jsonObj  = new JSONObject();
                JSONArray imgjson  = new JSONArray();
                for (int i = 0; i < job.getAttachImages().length; i++) {
                    imgjson.add(job.getAttachImages()[i]);
                }
                jsonObj.put("image_urls",imgjson);
//                jsonObj.put("prompt",badContent);
                jsonObj.put("aspect_ratio", whRaditoMaps.get("" + job.getWidth2height()));
                if(job.getProductMode()==1){
                    jsonObj.put("process_mode", "relax");
                }else {
                    jsonObj.put("process_mode", "fast");
                }

                jsonObj.put("webhook_endpoint", "https://www.shejiai.cc/api/v1/job/"+job.getId());
                jsonObj.put("webhook_secret", "");
                jsonObj.put("notify_progress", true);
                String jsonstr =jsonObj.toJSONString();
                log.info("图生图请求参数"+jsonstr);
                httpUtil.postJsonToString(doTaskUrl2, jsonstr, headers, new StateCallBack() {
                    @Override
                    public void onSuccess(String json) {
                        System.out.println("图生图 task:" + json);
                        JSONObject jsonObject = JSONObject.parseObject(json);
                        finalJob.setDataResult(json);
                        finalJob.setTaskId(jsonObject.getString("task_id"));
                        finalJob.setTaskRelationId(jsonObject.getString("task_id"));
                        jobRepository.save(finalJob);
                    }
                    @Override
                    public void onFail(String e) {
                        System.out.println("图生图请求参数 task error:" + e);
                        finalJob.setState(10);
                        finalJob.setErrorState(1);
                        finalJob.setNoticeState(1);
                        finalJob.setErrorMessages(e);
                        finalJob.setFinishTime(new Date());
                        jobRepository.save(finalJob);
                    }
                });
            }else {
                String imgurl="";
                for (int i = 0; i < job.getAttachImages().length; i++) {
                    imgurl+=job.getAttachImages()[i]+" ";
                }
                //文字生成
                addCmd +=whRatio;
                addCmd +=badContent;
                JSONObject jsonObj  = new JSONObject();
                jsonObj.put("prompt",imgurl+addCmd);
                jsonObj.put("aspect_ratio", whRaditoMaps.get("" + job.getWidth2height()));
                if(job.getProductMode()==1){
                    jsonObj.put("process_mode", "relax");
                }else {
                    jsonObj.put("process_mode", "fast");
                }
                jsonObj.put("webhook_endpoint", "https://www.shejiai.cc/api/v1/job/"+job.getId());
                jsonObj.put("webhook_secret", "");
                jsonObj.put("notify_progress", true);
                String jsonstr =jsonObj.toJSONString();
                log.info("文生图请求参数"+jsonstr);
                httpUtil.postJsonToString(doTaskUrl1, jsonstr, headers, new StateCallBack() {
                    @Override
                    public void onSuccess(String json) {
                        System.out.println("文生图 task:" + json);
                        JSONObject jsonObject = JSONObject.parseObject(json);
                        finalJob.setDataResult(json);
                        finalJob.setTaskId(jsonObject.getString("task_id"));
                        finalJob.setTaskRelationId(jsonObject.getString("task_id"));
                        jobRepository.save(finalJob);
                    }
                    @Override
                    public void onFail(String e) {
                        System.out.println("文生图 task error:" + e);
                        finalJob.setState(10);
                        finalJob.setErrorState(1);
                        finalJob.setNoticeState(1);
                        finalJob.setErrorMessages(e);
                        finalJob.setFinishTime(new Date());
                        jobRepository.save(finalJob);
                    }
                });
            }
        }

        if(job.getTaskType()==3){
            JSONObject jsonObj  = new JSONObject();
            jsonObj.put("origin_task_id",job.getTaskRelationId());
            jsonObj.put("index", job.getTaskTag());
            jsonObj.put("webhook_endpoint", "https://www.shejiai.cc/api/v1/job/"+job.getId());
            jsonObj.put("webhook_secret", "");
            jsonObj.put("notify_progress", true);
            String jsonstr =jsonObj.toJSONString();
            log.info("variation请求参数"+jsonstr);
            httpUtil.postJsonToString("https://api.goapi.xyz/mj/v2/variation", jsonstr, headers, new StateCallBack() {
                @Override
                public void onSuccess(String json) {
                    System.out.println("variation task:" + json);
                    JSONObject jsonObject = JSONObject.parseObject(json);
                    finalJob.setDataResult(json);
                    finalJob.setTaskId(jsonObject.getString("task_id"));
                    finalJob.setTaskRelationId(jsonObject.getString("task_id"));
                    jobRepository.save(finalJob);
                }
                @Override
                public void onFail(String e) {
                    System.out.println("variation task error:" + e);
                }
            });
        }
        if(job.getTaskType()==5){
            JSONObject jsonObj  = new JSONObject();
            jsonObj.put("image_url",job.getAttachImages()[0]);
            if(job.getProductMode()==1){
                jsonObj.put("process_mode", "relax");
            }else {
                jsonObj.put("process_mode", "fast");
            }
            jsonObj.put("webhook_endpoint", "https://www.shejiai.cc/api/v1/job/"+job.getId());
            jsonObj.put("webhook_secret", "");
            jsonObj.put("notify_progress", true);
            String jsonstr =jsonObj.toJSONString();
            log.info("describe请求参数"+jsonstr);
            httpUtil.postJsonToString("https://api.goapi.xyz/mj/v2/describe", jsonstr, headers, new StateCallBack() {
                @Override
                public void onSuccess(String json) {
                    System.out.println("describe task:" + json);
                    JSONObject jsonObject = JSONObject.parseObject(json);
                    finalJob.setDataResult(json);
                    finalJob.setTaskId(jsonObject.getString("task_id"));
                    finalJob.setTaskRelationId(jsonObject.getString("task_id"));
                    jobRepository.save(finalJob);
                }
                @Override
                public void onFail(String e) {
                    System.out.println("describe task error:" + e);
                }
            });
        }
        if(job.getTaskType()==8){
            JSONObject jsonObj  = new JSONObject();
            jsonObj.put("origin_task_id",job.getTaskRelationId());
            jsonObj.put("mask", job.getMask());
            jsonObj.put("prompt", addCmd);
            jsonObj.put("webhook_endpoint", "https://www.shejiai.cc/api/v1/job/"+job.getId());
            jsonObj.put("webhook_secret", "");
            jsonObj.put("notify_progress", true);
            String jsonstr =jsonObj.toJSONString();
            log.info("inpaint请求参数"+jsonstr);
            httpUtil.postJsonToString(doTaskUrl4, jsonstr, headers, new StateCallBack() {
                @Override
                public void onSuccess(String json) {
                    System.out.println("inpaint task:" + json);
                    JSONObject jsonObject = JSONObject.parseObject(json);
                    finalJob.setDataResult(json);
                    finalJob.setTaskId(jsonObject.getString("task_id"));
                    finalJob.setTaskRelationId(jsonObject.getString("task_id"));
                    jobRepository.save(finalJob);
                }
                @Override
                public void onFail(String e) {
                    System.out.println("inpaint task error:" + e);
                    finalJob.setState(10);
                    finalJob.setErrorState(1);
                    finalJob.setNoticeState(1);
                    finalJob.setErrorMessages(e);
                    finalJob.setFinishTime(new Date());
                    jobRepository.save(finalJob);
                }
            });
        }
        job = jobRepository.save(job);
        return job;
    }
    public static String toEnglishUrl(String raw) throws UnsupportedEncodingException {

        // String raw = "中国";
        String content = URLEncoder.encode(raw, "UTF-8");
        String salt = "1435660288";
        // my count
//        String secery = "fb5q0zbG1nfMBfLJpm4G";
//        String appid = "20230427001658492";
        // sheji count
        String secery = "oIcbPFyeSb1kx2NmpLkk";
        String appid = "20230427001658719";
        String testStr = appid + raw + salt + secery;
        String md5Hex1 = DigestUtil.md5Hex(testStr);
        String url = "http://api.fanyi.baidu.com/api/trans/vip/translate" +
                "?q=" + content + "&from=auto&to=en&appid=" + appid + "&salt=" + salt +
                "&sign=" + md5Hex1;
        return url;
    }

    public String hanleEngligh(String json) {
        JSONObject jsonObject = JSONObject.parseObject(json);
//            {"from":"zh","to":"en","trans_result":[{"src":"\u4e2d\u56fd","dst":"China"}]}
        JSONArray transResult = jsonObject.getJSONArray("trans_result");
        if (transResult == null || transResult.size() == 0)
            return null;
        String dst = transResult.getJSONObject(0).getString("dst");
        dst = dst.replaceAll("  ", " ");
        return dst;
    }

    public void doTask() throws Exception {

        List<Job> jobs = jobRepository.findNewByTaskState();
        if (jobs == null)
            return;
        if (System.currentTimeMillis() - lastDotask1 < 30000) {
            return;
        }
        lastDotask1 = System.currentTimeMillis();
        for (Job job: jobs) {
            create(job);
        }
    }
    public void task() {

        List<Job> list= jobRepository.findAllByTaskState();
        for (Job job: list) {
            gets(job.getId());
        }
    }
    public Job gets(@PathVariable("id") Long id) {

        Job job = jobRepository.findById(id).get();
        JSONObject jsonObj  = new JSONObject();
        jsonObj.put("task_id",job.getTaskId());
        String jsonstr =jsonObj.toJSONString();
        Map<String, String> headers = new HashMap<>();
        headers.put("X-API-KEY", Key);
        if(job.getState()==0||job.getState()==6||job.getState()==7||job.getState()==5){
            httpUtil.postJsonToString(doTaskUrl3, jsonstr, headers, new StateCallBack() {
                @Override
                public void onSuccess(String json) throws Exception {
                    JSONObject jsonObject = JSONObject.parseObject(json);
                    if (jsonObject.getString("status").equals("finished")) {
//                        job.setState(4);
                        JSONArray jsonArray  = new JSONArray();
                        jsonArray.add(jsonObject.getJSONObject("task_result").getString("image_url"));
//                        job.setFinalResult(jsonArray.toJSONString());
                        job.setResult(jsonArray.toJSONString());
                        job.setImageId(jsonObject.getJSONObject("task_result").getString("image_id"));

                        JSONArray jsonArray1  = new JSONArray();
                        jsonArray1.add(jsonObject.getJSONObject("task_result").getString("discord_image_url"));
                        job.setDiscordImageUrl(jsonObject.getJSONObject("task_result").getString("discord_image_url"));
                        System.out.println("查询结果 task:" + json);
                        json = "" + json;
                        job.setDataResult(json);
                        job.setState(2);
                        job.setFinishTime(new Date());
                        jobRepository.save(job);
                    }
                    if (jsonObject.getString("status").equals("failed")) {
                        Notice notice = new Notice();
                        notice.setJobId(job.getId());
                        notice.setContent("系统出错，带来不便，敬请谅解！请您重新提交任务。");
                        notice.setType(2);
                        notice.setStatus(0);
                        notice.setUserId(job.getUserId());
                        notice.setName("系统出错");
                        noticeRepository.save(notice);
                        job.setState(10);
                        job.setErrorState(1);
                        job.setNoticeState(1);
                        JSONArray jsonArray  = new JSONArray();
                        System.out.println("fetch task:" + json);
                        json = "" + json;
                        job.setErrorMessages(jsonObject.getJSONObject("task_result").getString("error_messages"));
                        job.setFinishTime(new Date());
                        jobRepository.save(job);

                    }

                }
                @Override
                public void onFail(String e) {
                    System.out.println("查询结果报错 error:" + e);
                    job.setState(10);
                    job.setErrorState(1);
                    job.setNoticeState(1);
                    job.setErrorMessages("系统错误");
                    job.setFinishTime(new Date());
                    jobRepository.save(job);
                }
            });
        }
        return job;
    }
    public void downloads(Job job) throws Exception {
        asynService.download(job);

    }
    public void doTask1() {

        Job job = jobRepository.findFirstByStateAndProductModeOrderByUpdateTimeAsc(0,deviceConfig.productMode);
        if (job == null)
            return;
        if (System.currentTimeMillis() - lastDotask1 < 30000) {
            return;
        }
        lastDotask1 = System.currentTimeMillis();

        String whRatio = " --ar 1:1";
        String temRadio = whRaditoMap.get("" + job.getWidth2height());
        if (temRadio != null) {
            whRatio = temRadio;
        }

        Integer module = job.getModule();
        String pictureWeight = job.getPictureWeight();
        if (pictureWeight == null) {
            pictureWeight = "";
        } else {
            pictureWeight = pictureWeight.trim();
        }
        pictureWeight = "";

        String tmpCmd1 = "";


        switch (module) {
            case 4:
                tmpCmd1 += "--v 5.1";
                break;
            case 5:
                tmpCmd1 += "--v 5.2";
                break;
            case 6:
                tmpCmd1 += "--v 5 --niji 5";
                break;
            case 7:
                tmpCmd1 += "--v 5 --test";
                break;
            case 8:
                tmpCmd1 += "--v 5 --testp";
                break;
        }

        String badContent = job.getBadContentFullText();
        if (badContent != null && !badContent.isEmpty() && !badContent.toLowerCase().equals("null")) {
            badContent = " --no " + badContent;
        } else {
            badContent = "";
        }
        badContent = badContent.replaceAll("  ", " ");


        String cmd = job.getFullTextCmd() + badContent + " " + tmpCmd1 + whRatio;
        if (job.getAttachment() != null) {
            cmd = job.getAttachment() + " " + job.getFullTextCmd() + badContent + " " + tmpCmd1 + whRatio;
        }

        String SERVER_ID = deviceConfig.SERVER_ID;
        String CHANNEL_ID = deviceConfig.CHANNEL_ID;
        String SESSION = deviceConfig.session;
        cmd = cmd.replace("  ", " ");
        String prompt = cmd.trim();
        //这里填写body
        String jsonstr = "{}";



        Map<String, String> headers = new HashMap<>();

        String auth = deviceConfig.auth;
        headers.put("authorization", auth);

        httpUtil.postJsonToString(doTaskUrl, jsonstr, headers, new StateCallBack() {
            @Override
            public void onSuccess(String json) {
//                if (json != null && json.length() > 50)
//                    json = json.substring(0, 50);
                System.out.println("do task:" + json);
                json = "" + json;
                if (json.isEmpty()) {
                    job.setState(1);
                    job.setPlateUserId(deviceConfig.userId);
                    job.setFinishTime(new Date(System.currentTimeMillis()));
                    jobRepository.save(job);
                }

            }

            @Override
            public void onFail(String e) {
                System.out.println("do task error:" + e);
            }
        });
    }


    public void redoTask() {

        Job job = jobRepository.findFirstByStateAndPlateUserIdAndProductModeOrderByUpdateTimeAsc(5, deviceConfig.userId, deviceConfig.productMode);
        if (job == null)
            return;
        if (System.currentTimeMillis() - lastDotask2 < 30000) {
            return;
        }
        lastDotask2 = System.currentTimeMillis();
        String SERVER_ID = deviceConfig.SERVER_ID;
        String CHANNEL_ID = deviceConfig.CHANNEL_ID;
        String message_id = job.getPlatformMessageId();
        String id = job.getTaskRelationId();
//        HashMap map=new HashMap();

        String jsonstr = "{" +
                "  \"type\": 3," +
                // "  \"nonce\": \"1099713452236079104\"," +
                "  \"guild_id\": \"" + SERVER_ID + "\"," +
                "  \"channel_id\": \"" + CHANNEL_ID + "\"," +
                "  \"message_flags\": 0," +
                "  \"message_id\": \"" + message_id + "\"," +
                "  \"application_id\": \"936929561302675456\"," +
                "  \"session_id\": \"99b40f40c23c9bab68b772890e8ea991\"," +
                "  \"data\": {" +
                "    \"component_type\": 2," +
                "    \"custom_id\": \"MJ::JOB::reroll::0::" + id + "::SOLO\"" +
                "  }" +
                "}";
        Map<String, String> headers = new HashMap<>();
        String auth = deviceConfig.auth;
        headers.put("authorization", auth);
        httpUtil.postJsonToString(doTaskUrl, jsonstr, headers, new StateCallBack() {
            @Override
            public void onSuccess(String json) {
                System.out.println("redo task:" + json);
                json = "" + json;
                if (json.isEmpty()) {
                    job.setState(1);
                    job.setPlateUserId(deviceConfig.userId);
                    job.setFinishTime(new Date(System.currentTimeMillis()));
                    jobRepository.save(job);
                }
            }

            @Override
            public void onFail(String e) {
                System.out.println("redo task error:" + e);
            }
        });
    }

    @Transactional
    public void cleanErrorTask() {
        jobRepository.updateJobsByStateAndFinalResult();
        jobRepository.updateJobsByStateAndFinalResult1();
        jobRepository.updateJobsByStateAndFinalResult2();
        jobRepository.updateJobsByStateAndFinalResult3();
    }


    public void noticeErrorTask() {

        List<Job> allByErrorStateAndNoticeState = jobRepository.findAllByErrorStateAndNoticeState(1, 0);
        allByErrorStateAndNoticeState.forEach(new Consumer<Job>() {
            @Override
            public void accept(Job job) {
                Notice notice = new Notice();
                notice.setJobId(job.getId());
                notice.setContent("系统出错，带来不便，敬请谅解！请您重新提交任务。");
                notice.setType(2);
                notice.setStatus(0);
                notice.setUserId(job.getUserId());
                notice.setName("系统出错");
                noticeRepository.save(notice);
                job.setNoticeState(1);
                jobRepository.save(job);
            }
        });

    }

    public void queryTask() throws Exception {
        if (true)
            return;
        String cookie = deviceConfig.cookie;
        String getImgUrl = deviceConfig.plateUrl;
        List<Job> allJob = jobRepository.findAllByStateAndPlateUserId(1, deviceConfig.userId);
        if (allJob.size() > 0) {
            Map<String, String> headers = new HashMap<>();
            headers.put("cookie", cookie);
            httpUtil.getToString(getImgUrl, headers, new StateCallBack() {
                @Override
                public void onSuccess(String json) {

                    String outJson = json;
                    if (outJson.length() > 500) {
                        outJson = outJson.substring(0, 500);
                    }
                    System.out.println("query data:" + outJson);
                    try {
                        JSONArray array = (JSONArray) JSONArray.parse(json);
                        Map<String, ArrayList<JSONObject>> map = new HashMap<>();
                        Map<String, ArrayList<String>> urlMap = new HashMap<>();

                        for (int i = 0; i < array.size(); i++) {

                            JSONObject jsonObject = array.getJSONObject(i);
                            JSONObject event = jsonObject.getJSONObject("event");
                            String id = jsonObject.getString("id");
                            JSONArray textPrompt = event.getJSONArray("textPrompt");
                            JSONArray imagePrompts = event.getJSONArray("imagePrompts");

                            if (imagePrompts == null) {
                                imagePrompts = new JSONArray();
                            }

                            String key = "";
                            if (textPrompt.size() != 0) {
                                key = (String) textPrompt.get(0);
                            }

                            ArrayList<String> urls = new ArrayList<>();
                            if (key.isEmpty())
                                for (int k = 0; k < imagePrompts.size(); k++) {
                                    try {
                                        String url = imagePrompts.getString(k);
                                        if (url == null)
                                            continue;
                                        url = httpUtil.getLocation(url);
                                        Thread.sleep(300);
                                        System.out.println("urlxx" + url);
                                        if (url != null) {
                                            urls.add(url);
                                        }
                                    } catch (Exception e) {
                                        System.out.println("net error");
                                        e.printStackTrace();
                                    }
                                }
                            urlMap.put(id, urls);
                            ArrayList<JSONObject> list = map.get(key);
                            if (list == null) {
                                list = new ArrayList<>();
                                map.put(key, list);
                            }
                            list.add(0, jsonObject);
                        }


                        System.out.println("alljob:" + allJob);
                        for (int k = 0; k < allJob.size(); k++) {
                            try {

                                Job job = allJob.get(k);


                                String cmd = job.getFullTextCmd().trim().replaceAll("  ", "");

                                cmd = cmd.trim();
                                ArrayList<JSONObject> jsonObjects = map.get(cmd);
                                if (jsonObjects == null) {
                                    System.out.println("not find json object");
                                    continue;
                                }
                                ArrayList list = new ArrayList();
                                for (int i = 0; i < jsonObjects.size(); i++) {
                                    JSONObject jsonObject = jsonObjects.get(i);
                                    JSONObject event = jsonObject.getJSONObject("event");
                                    String id = jsonObject.getString("id");
                                    JSONArray textPrompt = event.getJSONArray("textPrompt");
                                    String key = "";
                                    if (textPrompt.size() != 0) {
                                        key = (String) textPrompt.get(0);
                                    }
                                    String timeStr = jsonObject.getString("enqueue_time");
                                    String formatStr = "yyyy-MM-dd HH:mm:ss";
                                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(formatStr);
                                    try {
                                        Date date = simpleDateFormat.parse(timeStr);
                                        long beiTime = date.getTime() + 8 * 60 * 60 * 1000 + 3000;
                                        long time = job.getFinishTime().getTime();
                                        ArrayList<String> list1 = urlMap.get(id);
                                        boolean match = true;
                                        for (String url : list1) {
                                            String attachment = "" + job.getAttachment();
                                            System.out.println(attachment);
                                            attachment = attachment.replace(":443", "");
                                            url = url.replace(":443", "");
                                            if (!attachment.contains(url)) {
                                                match = false;
                                            } else {

                                            }
                                        }

                                        if (key.trim().equals(cmd) && match) {
                                            long abs = beiTime - time;
                                            System.out.println("abs:" + abs);
                                            if (abs < 0)
                                                continue;
                                            List<String> imagePaths = jsonObject.getJSONArray("image_paths").toJavaList(String.class);
                                            list.addAll(imagePaths);
                                            job.setResultImages(imagePaths);
                                            job.setTaskRelationId(jsonObject.getString("id"));
                                            job.setPlatformMessageId(jsonObject.getString("platform_message_id"));
                                            job.setState(2);
                                            job.setResultImages(list);
                                            job.setPlateId(id);
                                            if (!list.isEmpty()) {
                                                try {
                                                    jobRepository.save(job);
                                                } catch (Throwable throwable) {
                                                    throwable.printStackTrace();
                                                }
                                            }
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            } catch (Exception e) {
                                System.out.println("处理mid 失败");
                                e.printStackTrace();
                            }

                        }

                    } catch (Throwable e) {
                        System.out.println("请求mid出错了");
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFail(String e) {
                    System.out.println("query data error:" + e);
                }
            });
        }

    }

    public void download() throws Exception {

        List<Job> allByState = jobRepository.findAllByState(2);
        for (int i = 0; i < allByState.size(); i++) {
            Job job = allByState.get(i);
            asynService.download(job);
        }

    }

    public void nextDoTask() {

        Job job = jobRepository.findFirstByStateAndPlateUserIdAndProductModeOrderByUpdateTimeAsc(6, deviceConfig.userId, deviceConfig.productMode);
        if (job == null)
            return;
        if (System.currentTimeMillis() - lastDotask3 < 30000) {
            return;
        }
        lastDotask3 = System.currentTimeMillis();
        String SERVER_ID = deviceConfig.SERVER_ID;
        String CHANNEL_ID = deviceConfig.CHANNEL_ID;
        String message_id = job.getPlatformMessageId();
        String id = job.getTaskRelationId();
        String postionTag = job.getTaskTag();
        String jsonstr = "{" +
                "  \"type\": 3," +
                // "  \"nonce\": \"1129232301591363584\"," +
                "  \"guild_id\": \"" + SERVER_ID + "\"," +
                "  \"channel_id\": \"" + CHANNEL_ID + "\"," +
                "  \"message_flags\": 0," +
                "  \"message_id\": \"" + message_id + "\"," +
                "  \"application_id\": \"936929561302675456\"," +
                "  \"session_id\": \"" + deviceConfig.session + "\"," +
                "  \"data\": {" +
                "    \"component_type\": 2," +
                "    \"custom_id\": \"MJ::JOB::upsample::" + postionTag + "::" + id + "\"" +
                "  }" +
                "}";

        System.out.println("jsonstr:" + jsonstr);

        Map<String, String> headers = new HashMap<>();
        String auth = deviceConfig.auth;
        headers.put("authorization", auth);
        httpUtil.postJsonToString(doTaskUrl, jsonstr, headers, new StateCallBack() {
            @Override
            public void onSuccess(String json) {
                System.out.println("nextdo task:" + json);
                json = "" + json;
                if (json.isEmpty()) {
                    job.setState(1);
                    job.setPlateUserId(deviceConfig.userId);
                    job.setFinishTime(new Date(System.currentTimeMillis()));
                    jobRepository.save(job);
                }
            }

            @Override
            public void onFail(String e) {
                System.out.println("next job error:" + e);
            }
        });
    }

    public void nextDoVTask() {

        Job job = jobRepository.findFirstByStateAndPlateUserIdAndProductModeOrderByUpdateTimeAsc(7, deviceConfig.userId, deviceConfig.productMode);
        if (job == null)
            return;
        if (System.currentTimeMillis() - lastDotask4 < 30000) {
            return;
        }
        lastDotask4 = System.currentTimeMillis();
        String SERVER_ID = deviceConfig.SERVER_ID;
        String CHANNEL_ID = deviceConfig.CHANNEL_ID;
        Map<String, String> headers = new HashMap<>();
        String auth = deviceConfig.auth;
        headers.put("authorization", auth);
        String message_id = job.getPlatformMessageId();
        String id = job.getTaskRelationId();
        String postionTag = job.getTaskTag();
        String jsonstr = "{" +
                "  \"type\": 3," +
                // "  \"nonce\": \"1099872265366929408\"," +
                "  \"guild_id\": \"" + SERVER_ID + "\"," +
                "  \"channel_id\": \"" + CHANNEL_ID + "\"," +
                "  \"message_flags\": 0," +
                "  \"message_id\": \"" + message_id + "\"," +
                "  \"application_id\": \"936929561302675456\"," +
                "  \"session_id\": \"" + deviceConfig.session + "\"," +
                "  \"data\": {" +
                "    \"component_type\": 2," +
                "    \"custom_id\": \"MJ::JOB::variation::" + postionTag + "::" + id + "\"" +
                "  }" +
                "}";

        System.out.println("json:" + jsonstr);
        httpUtil.postJsonToString(doTaskUrl, jsonstr, headers, new StateCallBack() {
            @Override
            public void onSuccess(String json) {
                System.out.println("nextvdo task:" + json);
                json = "" + json;
                if (json.isEmpty()) {
                    job.setState(1);
                    job.setPlateUserId(deviceConfig.userId);
                    job.setFinishTime(new Date(System.currentTimeMillis()));
                    jobRepository.save(job);
                }

            }

            @Override
            public void onFail(String e) {
                System.out.println("next do v task error:" + e);
            }
        });

    }
}
